package cn.wolfcode.web.advice;

import cn.wolfcode.exception.BusinessException;
import cn.wolfcode.qo.JsonResult;
import com.alibaba.fastjson.JSON;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@ControllerAdvice
public class ExceptionControllerAdvice {
//    处理自定义异常
    @ExceptionHandler(BusinessException.class)
    public  void handleBusinessException(BusinessException e, HttpServletResponse response, HandlerMethod handlerMethod) throws IOException {
        e.printStackTrace();
//            分 AJKX和普通请求
        RequestBody methodAnnotation = handlerMethod.getMethodAnnotation(RequestBody.class);
        if(methodAnnotation == null){
            response.sendRedirect("/error");
        }
        else{
            response.setContentType("application/json;charset=utf-8");
            String jsonString = JSON.toJSONString(new JsonResult(false, e.getMessage()));
        response.getWriter().write(jsonString);
        }

    }

//  处理最大异常,从小异常开始处理
    @ExceptionHandler(Exception.class)
    public  void handleException(Exception e, HttpServletResponse response, HandlerMethod handlerMethod) throws IOException {
        e.printStackTrace();
//            分 AJKX和普通请求
        ResponseBody methodAnnotation = handlerMethod.getMethodAnnotation(ResponseBody.class);
        if(methodAnnotation == null){
            response.sendRedirect("/error");
        }
        else{
            response.setContentType("application/json;charset=utf-8");
            String jsonString = JSON.toJSONString(new JsonResult(false, "系统异常,稍后再试"));
            response.getWriter().write(jsonString);
        }

    }
}
